<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>用户管理</title>
  <link rel="stylesheet" href="css/style.css">
  <!-- Vue 3 & Element Plus -->
  <script src="./public/vue.global.prod.js"></script>
  <!-- 引入 Element Plus -->
  <link rel="stylesheet" href="./public/element-plus-index.css">
  <script src="./public/index.full.js"></script>
  <script src="./public/axios.min.js"></script>
  <style>
    .breadcrumb {
      color: #666;
      margin-bottom: 18px;
      font-size: 14px;
      font-weight: 500;
    }

    .card {
      background: #fff;
      border-radius: 6px;
      box-shadow: 0 2px 8px #f0f1f2;
      padding: 0 0 24px 0;
      margin-bottom: 24px;
      border: 1px solid #ebeef5;
    }

    .search-bar {
      display: flex;
      align-items: center;
      gap: 12px;
      background: #f5f7fa;
      padding: 18px 24px 12px 24px;
      border-radius: 6px 6px 0 0;
      border-bottom: 1px solid #ebeef5;
    }

    .add-btn {
      margin: 18px 0 0 24px;
    }

    .el-table {
      margin-top: 0;
    }

    .el-pagination {
      margin: 0 24px;
    }

    @media (max-width: 900px) {
      .container {
        max-width: 100vw;
      }

      .card,
      .breadcrumb {
        padding-left: 8px;
        padding-right: 8px;
      }

      .search-bar,
      .el-pagination {
        padding-left: 8px;
        padding-right: 8px;
      }
    }
  </style>
</head>

<body>
  <div id="app">
    <div class="container">
      <div class="breadcrumb">首页 / 用户管理</div>
      <div class="card">
        <div class="search-bar">
          <span style="font-size: 15px; color: #666;">用户名</span>
          <el-input v-model="searchName" placeholder="用户名" clearable @keyup.enter="searchUser" style="width: 200px"
            size="large"></el-input>
          <el-button type="primary" size="large" @click="searchUser">查询</el-button>
        </div>
        <el-button type="primary" class="add-btn" @click="addUser">
          添加用户
        </el-button>
        <el-table :data="pagedUsers" style="width: 100%; margin-top: 12px;" v-loading="loading" empty-text="暂无数据" border
          size="large">
          <el-table-column prop="loginId" label="登录Id" min-width="120"></el-table-column>
          <el-table-column prop="userId" label="用户Id" min-width="180"></el-table-column>
          <el-table-column prop="userName" label="用户名" min-width="120"></el-table-column>
          <el-table-column prop="role" label="角色" min-width="120"></el-table-column>
          <el-table-column prop="phone" label="手机号" min-width="120"></el-table-column>
          <el-table-column prop="email" label="邮箱" min-width="180"></el-table-column>
          <el-table-column label="操作" min-width="160">
            <template #default="scope">
              <el-button size="large" type="primary" @click="editUser(scope.row)">编辑</el-button>
              <el-button size="large" type="danger" @click="deleteUser(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="margin-top: 18px; text-align: right;">
          <el-pagination background layout="total, sizes, prev, pager, next" :total="filteredUsers.length"
            :page-size="pageSize" :page-sizes="[10, 20, 50, 100]" :current-page="page"
            @current-change="handlePageChange" @size-change="handleSizeChange" size="small"
            hide-on-single-page="true" />
        </div>
      </div>
      <!-- 添加用户弹窗 -->
      <el-dialog v-model="showAddUser" title="用户添加" width="600px" :close-on-click-modal="false"
        @close="handleAddUserDialogClose">
        <el-form :model="addForm" :rules="addRules" ref="addFormRef" label-width="90px" label-position="right">
          <el-form-item label="登录Id" prop="loginId" required>
            <el-input v-model="addForm.loginId" auto-complete="off" auto-complete="new-password"></el-input>
          </el-form-item>
          <el-form-item label="用户名" prop="userName" required>
            <el-input v-model="addForm.userName" :readonly="addUserNameReadonly"
              @click="addUserNameReadonly = false"></el-input>
          </el-form-item>
          <el-form-item label="角色" prop="role" required>
            <el-radio-group v-model="addForm.role">
              <el-radio label="系统管理员">系统管理员</el-radio>
              <el-radio label="运营人员">运营人员</el-radio>
              <el-radio label="普通后台用户">普通后台用户</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="密码" prop="password" required>
            <el-input v-model="addForm.password" type="password" auto-complete="off"
              auto-complete="new-password"></el-input>
            <div style="color:#888;font-size:12px;margin-top:2px;">
              (大写字母、小写字母、数字、特殊字符，以上至少包含两项)
            </div>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="addForm.phone" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="showAddUser = false">取消</el-button>
          <el-button type="primary" @click="submitAddUser">保存</el-button>
        </template>
      </el-dialog>
      <!-- 编辑用户弹窗 -->
      <el-dialog v-model="showEditUser" title="用户编辑" width="600px" :close-on-click-modal="false">
        <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="90px" label-position="right">
          <el-form-item label="登录Id" prop="loginId" required>
            <el-input v-model="editForm.loginId" autocomplete="off" disabled></el-input>
          </el-form-item>
          <el-form-item label="用户名" prop="userName" required>
            <el-input v-model="editForm.userName" autocomplete="off" disabled></el-input>
          </el-form-item>
          <el-form-item label="角色" prop="role" required>
            <el-radio-group v-model="editForm.role">
              <el-radio label="系统管理员">系统管理员</el-radio>
              <el-radio label="运营人员">运营人员</el-radio>
              <el-radio label="普通后台用户">普通后台用户</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="editForm.password" type="password" show-password autocomplete="off"></el-input>
            <div style="color:#888;font-size:12px;margin-top:2px;">
              (大写字母、小写字母、数字、特殊字符，以上至少包含两项)
            </div>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="editForm.phone" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="showEditUser = false">取消</el-button>
          <el-button type="primary" @click="submitEditUser">保存</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
  <script>
    const { createApp, computed, ref, watch, onMounted } = Vue
    const { ElMessageBox, ElMessage } = ElementPlus

    // 角色映射
    const roleMap = {
      0: '普通后台用户',
      1: '运营人员',
      2: '系统管理员'
    }
    const roleReverseMap = {
      '普通后台用户': 0,
      '运营人员': 1,
      '系统管理员': 2
    }

    // // 用户userid映射
    // const userIdMap = {
    //   elan: "1920671768591339520",
    //   mary: "1931987987453841408",
    //   sunny: "1920775200157339648",
    //   admin: "1929803662620758016"
    // }

    // 全局token获取函数
    function getToken () {
      return sessionStorage.getItem('token')
    }

    createApp({
      setup () {
        const searchName = ref('')
        const page = ref(1)
        const pageSize = ref(10)
        const loading = ref(false)
        const users = ref([])
        // 添加用户弹窗相关
        const showAddUser = ref(false)
        const addUserNameReadonly = ref(true)
        const addFormRef = ref()
        const addForm = ref({
          loginId: '',
          userName: '',
          role: '系统管理员',
          password: '',
          email: '',
          phone: ''
        })
        const addRules = {
          loginId: [{ required: true, message: '请输入登录Id', trigger: 'blur' }],
          userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
          role: [{ required: true, message: '请选择角色', trigger: 'change' }],
          password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        }
        const showEditUser = ref(false)
        const editFormRef = ref()
        const editForm = ref({
          loginId: '',
          userName: '',
          role: '系统管理员',
          password: '',
          email: '',
          phone: ''
        })
        const editRules = {
          userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
          role: [{ required: true, message: '请选择角色', trigger: 'change' }],
          password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        }

        // 获取用户列表
        async function fetchUsers () {
          loading.value = true
          try {
            const res = await axios.get('/user', {
              headers: {
                'Authorization':  getToken()
              }
            })
            if (res.data.status === 'OK') {
              console.log(res.data.entities, "res.data.entities")

              // entities为数组
              users.value = (res.data.entities || []).map(u => ({
                ...u,
                loginId: u.username,
                userId: u.userId,
                // userId: userIdMap[u.username] || '', // 接口问题这里先使用映射过来的
                userName: u.nickname,
                role: roleMap[u.role] || u.role,
                email: u.email || '',
                phone: u.phone || ''
              }))
            } else {
              ElMessage.error('获取用户失败')
            }
          } catch (e) {
            ElMessage.error('获取用户失败: ' + (e.response?.data?.message || e.message))
          } finally {
            loading.value = false
          }
        }

        // 新增用户
        async function submitAddUser () {
          addFormRef.value.validate(async (valid) => {
            if (valid) {
              try {
                const res = await axios.post(
                  '/user',
                  {
                    username: addForm.value.loginId,
                    password: addForm.value.password,
                    nickname: addForm.value.userName,
                    role: roleReverseMap[addForm.value.role]
                  },
                  {
                    headers: {
                      'Content-Type': 'application/json',
                      'Authorization': getToken()
                    }
                  }
                )
                if (res.data.status === 'OK') {
                  ElMessage.success('添加成功')
                  showAddUser.value = false
                  await fetchUsers()
                  // 重置表单
                  addForm.value = {
                    loginId: '',
                    userName: '',
                    role: '系统管理员',
                    password: '',
                    email: '',
                    phone: ''
                  }
                } else {
                  ElMessage.error('添加失败')
                }
              } catch (e) {
                ElMessage.error('添加失败: ' + (e.response?.data?.message || e.message))
              }
            }
          })
        }

        // 删除用户
        async function deleteUser (user) {
          try {
            await ElMessageBox.confirm(
              `确定要删除用户 "${user.userName}" 吗？`,
              '提示',
              {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
              }
            )
            const res = await axios.delete(`/user/${user.userId}`, {
              headers: {
                'Authorization': getToken()
              }
            })
            if (res.data.status === 'OK' && res.data.entity === true) {
              ElMessage.success('删除成功')
              await fetchUsers()
            } else {
              ElMessage.error('删除失败')
            }
          } catch (e) {
            if (e !== 'cancel') {
              ElMessage.error('删除失败: ' + (e.response?.data?.message || e.message))
            }
          }
        }

        // 编辑用户
        async function editUser (user) {
          // 打开弹窗并填充表单
          editForm.value = {
            loginId: user.loginId,
            userId: user.userId,
            userName: user.userName,
            role: user.role,
            password: '',
            email: user.email,
            phone: user.phone
          }
          showEditUser.value = true
        }

        // 提交编辑
        async function submitEditUser () {
          editFormRef.value.validate(async (valid) => {
            if (valid) {
              try {
                const userId = editForm.value.userId // 直接用
                const payload = {
                  password: editForm.value.password, // 必须
                  role: roleReverseMap[editForm.value.role], // 必须
                }
                if (editForm.value.userName) payload.nickname = editForm.value.userName
                if (editForm.value.email) payload.email = editForm.value.email
                if (editForm.value.phone) payload.phone = editForm.value.phone

                const res = await axios.put(`/user/${userId}`, payload, {
                  headers: {
                    'Content-Type': 'application/json',
                    'Authorization': getToken()
                  }
                })
                if (res.data.status === 'OK' && res.data.entity === true) {
                  ElMessage.success('编辑成功')
                  showEditUser.value = false
                  await fetchUsers()
                } else {
                  ElMessage.error('编辑失败')
                }
              } catch (e) {
                ElMessage.error('编辑失败: ' + (e.response?.data?.message || e.message))
              }
            }
          })
        }

        // 搜索和分页
        const filteredUsers = computed(() => {
          if (!searchName.value) return users.value
          return users.value.filter(u =>
            u.userName.includes(searchName.value) ||
            u.loginId.includes(searchName.value)
          )
        })
        const maxPage = computed(() =>
          Math.max(1, Math.ceil(filteredUsers.value.length / pageSize.value))
        )
        const pagedUsers = computed(() => {
          const start = (page.value - 1) * pageSize.value
          return filteredUsers.value.slice(start, start + pageSize.value)
        })

        function searchUser () {
          page.value = 1
        }
        function addUser () {
          addForm.value = {
            loginId: '',
            userName: '',
            role: '系统管理员',
            password: '',
            email: '',
            phone: ''
          }
          showAddUser.value = true
          addUserNameReadonly.value = true
          addFormRef.value && addFormRef.value.resetFields && addFormRef.value.resetFields()
        }
        function handleAddUserDialogClose () {
          addForm.value = {
            loginId: '',
            userName: '',
            role: '系统管理员',
            password: '',
            email: '',
            phone: ''
          }
          addUserNameReadonly.value = true
          addFormRef.value && addFormRef.value.resetFields && addFormRef.value.resetFields()
        }
        function handlePageChange (val) {
          page.value = val
        }
        function handleSizeChange (val) {
          pageSize.value = val
          page.value = 1 // 切换每页条数时回到第一页
        }
        // 保证分页不越界
        watch(filteredUsers, () => {
          if (page.value > maxPage.value) page.value = maxPage.value
        })

        onMounted(fetchUsers)

        return {
          searchName,
          page,
          pageSize,
          users,
          filteredUsers,
          pagedUsers,
          maxPage,
          loading,
          searchUser,
          addUser,
          handleAddUserDialogClose,
          editUser,
          deleteUser,
          handlePageChange,
          // 添加用户相关
          showAddUser,
          addForm,
          addFormRef,
          addRules,
          submitAddUser,
          // 编辑用户相关
          showEditUser,
          editForm,
          editFormRef,
          editRules,
          submitEditUser,
          addUserNameReadonly,
        }
      }
    }).use(ElementPlus).mount('#app');
  </script>

</body>

</html>